package com.aaa.spring.controller;

import com.aaa.spring.exception.BizException;
import com.aaa.spring.pojo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class ErrorController {
    //日志log对象
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 405异常
     * @param e
     * @return
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class) //要被捕获的异常
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) //响应状态 405 404 500
    public Result httpRequestMethodNotSupportedException(Exception e) {
        log.error(e.getMessage(), e);
        return new Result(405, "请求不支持");
    }
    /**
     * 404异常
     * @param e
     * @return
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Result handlerNoFoundException(Exception e) {
        log.error(e.getMessage(), e);
        return new Result(404,"未找到");
    }
    /**
     * 业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result handleBizException(BizException e) {
        log.error(e.getMessage(), e);
        return new Result(e.getCode(),e.getMsg());
    }
    /**
     * 系统异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result handleException(Exception e) {
        log.error(e.getMessage(), e);
        return new Result(500,"系统繁忙~~稍后再试");
    }

}
